from PIL import Image
import numpy as np

def add_noise(image_path, output_path, noise_factor):
    # 读取图像
    img = Image.open(image_path).convert('L')  # 转换为灰度图
    img_array = np.array(img)

    # 添加随机噪音
    rows, cols = img_array.shape
    noise = np.random.normal(0, noise_factor, (rows, cols))
    noise = noise.astype('uint8')  # 确保噪音值在0-255之间
    img_array = np.clip(img_array + noise, 0, 255)  # 防止像素值超出范围

    # 将修改后的数组转换回图像
    noisy_img = Image.fromarray(img_array)

    # 保存图像
    noisy_img.save(output_path)

# 使用函数
add_noise('C:/Users\86178\Desktop\数字图像/numpy_calculation_question_set-master/numpy_calculation_question_set-master/dog.jpg', 'C:/Users\86178\Desktop\数字图像/numpy_calculation_question_set-master/numpy_calculation_question_set-master/dog_chu.jpg', 20)






